/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package exemple;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

/**
 *
 * @author root
 */
public class ProcessusImpl extends UnicastRemoteObject implements Service {
    
    private Process proc;
    private InputStream stdin;
    private InputStreamReader isr;
    private BufferedReader br;
    private int id_process;
    private int id_historic;
    private ProcessusB p;
    private int pid;
    private String nameUser;
    private String nameProcess;
    private double cpu_use_process;
    private double ram_use_process;
    
    public ProcessusImpl() throws RemoteException{
    }
    
    public List<ProcessusB> getListProcessus() throws RemoteException {
        
        List<ProcessusB> listProcess = new ArrayList<>();
        
        //Récupère les processus
	try {            
            String[] cmd = {
                "/bin/sh",
                "-c",
                "top -b -n1 | sed 's/^[ \\s]*//g' | sed 's/\\ \\ */;/g' | cut -d';' -f 1,2,9,10,12 | tail -n +8"
            };

            proc = Runtime.getRuntime().exec(cmd);
            stdin = proc.getInputStream();
            isr = new InputStreamReader(stdin);
            br = new BufferedReader(isr);
            String line;
            String[] temp;
            
            while ( (line = br.readLine()) != null) {
                temp = line.split(";");
                pid= Integer.parseInt(temp[0]);
                nameUser=temp[1];
                cpu_use_process=Double.parseDouble(temp[2].replace(",", "."));
                ram_use_process=Double.parseDouble(temp[3].replace(",", "."));
                nameProcess=temp[4];            
                p = new ProcessusB(id_process,nameProcess,pid,nameUser,cpu_use_process,ram_use_process);
                listProcess.add(p);
            }
            int exitVal = proc.waitFor();            
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return listProcess;
        
//        try
//        {            
//            Runtime rt = Runtime.getRuntime();
//            String[] cmd = {
//                "/bin/sh",
//                "-c",
//                "top -b -n1 | sed 's/^[ \\s]*//g' | sed 's/\\ \\ */;/g' | cut -d';' -f 1,2,9,10,12"
//            };
//
//            Process proc = Runtime.getRuntime().exec(cmd);
//
//            String command = "top -b -n1 | sed 's/^[ \\s]*//g' '|' sed 's/\\ \\ */;/g' '|' cut -d';' -f 1,2,9,10,12";
//            Process proc = rt.exec(command);
//            InputStream stderr = proc.getErrorSSystemInformationsBeantream();
//            InputStreamReader isr = new InputStreamReader(stderr);
//            BufferedReader br = new BufferedReader(isr);
//            String line = null;
//            System.out.println("<ERROR>");
//            while ( (line = br.readLine()) != null)
//                System.out.println(line);
//            System.out.println("</ERROR>");
//            int exitVal = proc.waitFor();
//            System.out.println("Process exitValue: " + exitVal);
//        } catch (Throwable t)
//          {
//            t.printStackTrace();
//          }   
    }
    
    public HistoricSystem getSystemInformations() throws RemoteException {
        //Récupère la quantité de mémoire libre et le pourcentage de CPU utilisé
        HistoricSystem hi = null;
        try {            
            String[] cmd = {
                "/bin/sh",
                "-c",
                "top -b -n1 | head -n 4 | tail -n +3"
            };

            proc = Runtime.getRuntime().exec(cmd);
            stdin = proc.getInputStream();
            isr = new InputStreamReader(stdin);
            br = new BufferedReader(isr);
            String line;
            
            double cpuUse = 0;
            double memFree = 0;
            
            while ( (line = br.readLine()) != null) {
                //Supprime les espaces avant et après la chaine
                //Remplace la virgule par un point
                //Converti en float
                if(line.indexOf("%Cpu(s):")>-1) {
                    cpuUse = Double.parseDouble(line.substring(line.indexOf(":")+1, line.indexOf( "us" )).trim().replace(",", "."));
                    cpuUse += Double.parseDouble(line.substring(line.indexOf("us,")+3, line.indexOf( "sy" )).trim().replace(",", "."));
                }
                else if(line.indexOf("KiB Mem:")>-1) {
                    memFree = Double.parseDouble(line.substring(line.indexOf( "used," )+5, line.indexOf( "free" )).trim().replace(",", "."));
                }
            }
            DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            Date date = new Date();
            hi = new HistoricSystem(id_historic,dateFormat.format(date),cpuUse,memFree);
            System.out.println(hi);
            int exitVal = proc.waitFor();            
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return hi;
    }
}